import {
  AlipayOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoOutlined,
  UserOutlined,
  WeiboOutlined,
} from "@ant-design/icons";
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from "@ant-design/pro-components";
import { Button, Divider, Space, Tabs, message, theme as antdThemeToken, Switch, ConfigProvider } from "antd";
import type { TabsProps } from 'antd';
import type { CSSProperties } from "react";
import { useState } from "react";
import { Icon } from '@iconify/react';
import { useThemeStore, userStore } from "@/store";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";

import "./index.scss"
import { fetchPermissionListAPI } from "@/apis/permission";

type LoginType = "phone" | "account";



const iconStyles: CSSProperties = {
  color: "rgba(0, 0, 0, 0.2)",
  fontSize: "18px",
  verticalAlign: "middle",
  cursor: "pointer",
}



const Page = () => {
  const [loginType, setLoginType] = useState<LoginType>("account")
  const { token } = antdThemeToken.useToken()
  const { theme } = useThemeStore()
  const { t } = useTranslation()
  const { user, fetchLogin, fetchUserInfo, fetchPermission } = userStore()
  const navigate = useNavigate();

  const tabItems: TabsProps['items'] = [
    {
      key: 'account',
      label: t('account password login'),
    },
    {
      key: 'phone',
      label: t('phone number login'),
    }
  ];

  return (
    <div
      style={{
        backgroundColor: "white",
        height: "100vh",
      }}
    >
      <LoginFormPage
        backgroundImageUrl={theme === 'light' ? 'https://image.xiaosaturn.com/Photo/2023126/211505/7h0k62w53sbackground-7842730.jpg' : ''}
        logo="https://image.xiaosaturn.com/random-avatar/2023920/9354/q2S1cLx5xvUBhP7i.png"
        backgroundVideoUrl={theme === 'dark' ? 'https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr' : ''}
        title={t('login title')}
        containerStyle={{
          backgroundColor: theme === 'light' ? 'rgba(255, 255, 255, 0.1)' : "rgba(0, 0, 0, 0.1)",
          backdropFilter: "blur(4px)",
        }}
        style={{
          flex: 'initial'
        }}
        subTitle={t('login sub title')}
        onFinish={async (e) => {
            message.loading({
              content: t('login loading'),
              duration: 0,
              key: 'loading'
            })
            const res = await fetchLogin(e)
            message.destroy('loading')
            if (res.code != 0) {
              // 提示登录失败
              message.error(res.msg);
            } else {
              // 跳转首页,提示登录成功
              navigate('/');
              message.success(t('login success'));
            }
        }}
      >
        <Tabs
          centered
          activeKey={loginType}
          onChange={(activeKey) => setLoginType(activeKey as LoginType)}
          items={tabItems}
        ></Tabs>
        {loginType === "account" && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: "large",
                prefix: (
                  <UserOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={"prefixIcon"}
                  />
                ),
              }}
              placeholder={t('account placeholder')}
              rules={[
                {
                  required: true,
                  message: t('account placeholder'),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: "large",
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={"prefixIcon"}
                  />
                ),
              }}
              placeholder={t('password placeholder')}
              rules={[
                {
                  required: true,
                  message: t('password placeholder'),
                },
              ]}
            />
          </>
        )}
        {loginType === "phone" && (
          <>
            <ProFormText
              fieldProps={{
                size: "large",
                prefix: (
                  <MobileOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={"prefixIcon"}
                  />
                ),
              }}
              name="mobile"
              placeholder={t('phone placeholder')}
              rules={[
                {
                  required: true,
                  message: t('phone placeholder'),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: t('phone format error'),
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: "large",
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={"prefixIcon"}
                  />
                ),
              }}
              captchaProps={{
                size: "large",
              }}
              placeholder={t('password placeholder')}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${t('get captcha')}`;
                }
                return t('get captcha');
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: t('captcha placeholder'),
                },
              ]}
              onGetCaptcha={async () => {
                // message.success("获取验证码成功！验证码为：1234");
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            {t('auto login label')}
          </ProFormCheckbox>
          <a
            style={{
              float: "right",
            }}
          >
            {t('forgot password label')}
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

const TopRight = () => {
  const { theme, changeTheme } = useThemeStore()
  const { t } = useTranslation()
  const changeLanguage = () => {
    const language = localStorage.getItem('language')
    if (language === 'en') {
      localStorage.setItem('language', 'cn')
    } else {
      localStorage.setItem('language', 'en')
    }
    window.location.reload()
  }
  return (
    <div className="top-right">
      <Switch
        checked={theme === 'dark'}
        onChange={(value) => changeTheme(value ? 'dark' : 'light')}
        checkedChildren={t('dark mode')}
        unCheckedChildren={t('light mode')}
        style={{ marginRight: 10 }}
      />
      <span className="user-language" style={{ marginRight: 10, color: theme === 'light' ? '#001529' : '#fff', borderColor: theme === 'light' ? '#001529' : '#fff' }} onClick={changeLanguage}>
        <Icon icon="ic:baseline-language" color={theme === 'light' ? '#001529' : '#fff'} width={20} />
        <span>{t('language')}</span>
      </span> 
    </div>
  );
}
const ProConfigPage = () => {
  const { theme } = useThemeStore();
  return (
    <ConfigProvider theme={{
      token: {
        colorPrimary: '#00b96b',
        // colorBorderSecondary: '#00b96b',
        colorPrimaryText: '#00b96b',
        colorTextBase: theme === 'light' ? '#001529' : '#fff',
        colorBorder: theme === 'light' ? '#001529' : '#fff',
        colorBgBase: theme === 'light' ? '#fff' : '#001529',
        colorBgContainer: theme === 'light' ? '#fff' : '#001529',
        colorBgLayout: theme === 'light' ? '#fff' : '#000b15', // #000b15
      },
      components: {
        Switch: {
          trackHeight: 30,
          handleSize: 26,
          trackMinWidth: 70,
          innerMinMargin: 2,
        },
      },
    }}>
      <ProConfigProvider dark={theme == "dark" ? true : false}>
        <Page />
      </ProConfigProvider>
      <TopRight />
    </ConfigProvider>
   
  );
};

export default ProConfigPage
